package starfire.task;

import java.net.*;

import starfire.ftp.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author zzzhc.starfire@gmail.com
 * @version 1.0
 */

public class FtpTaskDescription
    extends TaskDescription {
  FtpSite site = null;
  FtpFile remoteFile = null;
  long totalLength = -1L;

  public FtpTaskDescription(URL url) {
    super(url);
  }

  public FtpTaskDescription(URL url, String localPath) {
    super(url, localPath);
  }

  public FtpTaskDescription(FtpSite site, FtpFile remoteFile) {
    super();
    this.site = site;
    this.remoteFile = remoteFile;
    remotePath = remoteFile.getPath();
    totalLength = remoteFile.length();
   // this.setLocalePath(remoteFile.getName());
  }

  public FtpSite getFtpSite() {
    return site;
  }

  public FtpFile getRemoteFile() {
    return remoteFile;
  }

  protected void parseURL(URL url) {
    taskURL = url;
    setProtocol(url.getProtocol());
    setHost(url.getHost());
    site = new FtpSite(getHost());
    int port = url.getPort();
    if (port == -1) {
      port = FtpSite.DEFAULTPORT;
    }
    this.port = port;
    site.setPort(port);
    String userInfo = url.getUserInfo();
    if (userInfo == null || userInfo.indexOf(':') == -1) {
      userName = FtpSite.DEFAULTUSER;
      password = FtpSite.DEFAULTPASSWORD;
    }
    else {
      int index = userInfo.indexOf(':');
      userName = userInfo.substring(0, index);
      password = userInfo.substring(index + 1);
      site.setUser(userName);
      site.setPassword(password);
    }
    remotePath = url.getPath();
  }

  public URL getTaskURL()
  {
    if (taskURL==null)
    {
      try
      {
        if (site.getUser().equals("anonymous"))
          taskURL = new URL("ftp", site.getHost(), site.getPort(),
                          remoteFile.getPath());
        else
          taskURL = new URL("ftp://"+site.getUser()+":"+
                            site.getPassword()+"@"+site.getHost()+
                            ":"+site.getPort()+remoteFile.getPath());
      }catch (Exception e)
      {
        e.printStackTrace();
      }
    }
    return taskURL;
  }

  public String getLocalePath()
  {
    String s = super.getLocalePath();
    if (s==null)
      s = remoteFile.getName();
    return s;
  }

  public String toString()
  {
    taskURL = getTaskURL();
    return taskURL.toString();
  }
}